package com.wyclabs.gateway.auth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

/**
 * Security配置
 * @author YichuanWang
 * @date 2019/11/13 11:05
 */
@EnableWebFluxSecurity
public class SecurityConfig {

    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired
    private AuthenticationFailHandler authenticationFailHandler;
    @Autowired
    private CustomizeAuthenticationEntryPoint customizeAuthenticationEntryPoint;
    //security的鉴权排除的url列表
    private static final String[] excludedAuthPages = {
            "/auth/login", "/auth/logout", "/health", "/api/socket/**",
            "/actuator/**", "/instances", "/auth/**", "/oauth/**"
    };

    @Bean
    public SecurityWebFilterChain webFluxSecurityFilterChain(ServerHttpSecurity http) throws Exception {
        http.authorizeExchange()
                .pathMatchers(excludedAuthPages).permitAll()  //无需进行权限过滤的请求路径
                .pathMatchers(HttpMethod.OPTIONS).permitAll() //option 请求默认放行
                .anyExchange().authenticated()
                .and()
                .httpBasic()
                .and()
                .formLogin().loginPage("/auth/login")
//                .authenticationSuccessHandler(authenticationSuccessHandler) //认证成功
//                .authenticationFailureHandler(authenticationFaillHandler) //登陆验证失败
                .and().exceptionHandling().authenticationEntryPoint(customizeAuthenticationEntryPoint)  //基于http的接口请求鉴权失败
                .and().csrf().disable()
                .logout().disable();
        return http.build();
    }


}
